/**
 * 
 */
package com.alstudio.view.listview;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.format.DateUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.module.user.UserHomePageAcitivty;
import com.alstudio.utils.absListView.loadmore.AbsListViewLoadMoreManager;
import com.alstudio.utils.absListView.loadmore.OnLoadMoreListener;
import com.alstudio.utils.activity.ALActivityManager;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.ViewUtils;
import com.alstudio.view.absadapter.ViewAdapter;
import com.alstudio.view.toast.MyToastUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.extras.SoundPullEventListener;
import com.loovee.imaohu.R;

/**
 * @author alonso lee
 * 
 */
public class PullRefreshAndLoadMoreView extends LinearLayout implements
		OnItemClickListener {

	private PullToRefreshListView mPullRefreshListView;
	private ListView mListView;
	private ViewAdapter adapter;

	// 起始请求
	public int startIndex = ALLocalEnv.LOAD_MORE_START_INDEX;;
	// 结束请求
	public int endIndex = ALLocalEnv.LOAD_MORE_END_INDEX;

	private AbsListViewLoadMoreManager loadMoreManager;

	LayoutInflater inflater;
	private boolean isRefreshing = false;

	private RankViewLoadStateListener loadStateListener;
	private View header;

	private int requestType = -1;

	private boolean enableSoundListener = true;

	private SoundPullEventListener<ListView> soundListener;
	// // 是否允许监听item点击事件
	// private boolean enableItemClickListener = true;

	// 无数据的布局
	private View noDataLayout;
	// 无数据显示的图片
	private ImageView noDataImg;
	private TextView noDataInfo;
	// 超时20S
	private final int REQUEST_TIME_OUT = 20 * 1000;
	
	private boolean isLocalData = false;

	// 超时处理
	private Handler mHandler = new Handler();

	private void startTimer() {
		mHandler.postDelayed(requestTimeoutTask, REQUEST_TIME_OUT);
	}

	private void stopTimer() {
		mHandler.removeCallbacks(requestTimeoutTask);
	}

	private Runnable requestTimeoutTask = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			onLoadCompleted();
			MyToastUtil.getInstance().showCenterToastOnCenter(
					R.string.TxtLoadFail);
		}
	};

	private void addSoundListener() {
		/**
		 * Add Sound Event Listener
		 */
		soundListener = new SoundPullEventListener<ListView>(
				ALLocalEnv.getLocalEnv());
		soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
		soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
		soundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);
		// mPullRefreshListView.setOnPullEventListener(soundListener);
		setupRefreshSoundListener(enableSoundListener);
	}

	public interface RankViewLoadStateListener {
		// 底部加载更多
		public void onLoadMore(PullRefreshAndLoadMoreView view);

		// 重新刷新
		public void onRefresh(PullRefreshAndLoadMoreView view);
	}

	private OnLoadMoreListener loadMoreListener = new OnLoadMoreListener() {

		@Override
		public void onLoadMore() {
			// TODO Auto-generated method stub
			setLoadIndex(false);
			if(!isLocalData){
				if(!ALLocalEnv.isSendXmppDataEnable()){
					onLoadCompleted();
					return;
				}
			}
			if (loadStateListener != null) {
				ALLog.d("已到底部，回调通知开始加载更多");
				startTimer();
				loadStateListener.onLoadMore(PullRefreshAndLoadMoreView.this);
			}
		}
	};

	/**
	 * @param context
	 */
	public PullRefreshAndLoadMoreView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub

		initView(context);
	}

	public PullRefreshAndLoadMoreView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	/**
	 * @param context
	 */
	public PullRefreshAndLoadMoreView(Context context, ViewAdapter adapter) {
		super(context);
		this.adapter = adapter;
		initView(context);
	}

	/**
	 * @param context
	 */
	public PullRefreshAndLoadMoreView(Context context, ViewAdapter adapter,
			View header) {
		super(context);
		this.adapter = adapter;
		this.header = header;
		initView(context);
	}

	public ListView getListView() {
		return mListView;
	}

	/**
	 * @param enableSoundListener
	 *            the enableSoundListener to set
	 */
	public void setEnableRefreshSound(boolean isEnableRefreshSound) {
		this.enableSoundListener = isEnableRefreshSound;
		setupRefreshSoundListener(isEnableRefreshSound);
	}

	/**
	 * @return the enableSoundListener
	 */
	public boolean isEnableRefreshSound() {
		return enableSoundListener;
	}

	/**
	 * @param adapter
	 *            the adapter to set
	 */
	public void setAdapter(ViewAdapter adapter) {
		this.adapter = adapter;
		mListView.setAdapter(adapter);
	}

	/**
	 * @return the adapter
	 */
	public ViewAdapter getAdapter() {
		return adapter;
	}

	/**
	 * @param requestType
	 *            the requestType to set
	 */
	public void setRequestType(int requestType) {
		this.requestType = requestType;
	}

	/**
	 * 监听加载更多、重新加载事件
	 * 
	 * @param loadStateListener
	 *            the loadStateListener to set
	 */
	public void setLoadStateListener(RankViewLoadStateListener loadStateListener) {
		this.loadStateListener = loadStateListener;
	}

	/**
	 * 刷新完成
	 */
	public void onLoadCompleted() {
		isRefreshing = false;
		loadMoreManager.onLoadMoreComplete();
		mPullRefreshListView.onRefreshComplete();
		stopTimer();
	}

	/**
	 * 家在更多完毕
	 */
	public void onLoadMoreCompleted() {
		loadMoreManager.onLoadMoreComplete();
	}

	public void onRefreshCompleted() {
		mPullRefreshListView.onRefreshComplete();
	}

	/**
	 * 禁止下拉刷新
	 */
	public void disablePullRefresh() {
		mPullRefreshListView.setMode(Mode.DISABLED);
	}

	/**
	 * 开启下拉刷新
	 */
	public void enablePullRefresh() {
		mPullRefreshListView.setMode(Mode.PULL_FROM_START);
	}

	/**
	 * 更新是否滑动加载更多
	 * 
	 * @param hasMore
	 */
	public void updateLoadMoreState(boolean hasMore) {
		if (hasMore) {
			loadMoreManager.setOnLoadMoreListener(loadMoreListener);
		} else {
			loadMoreManager.setOnLoadMoreListener(null);
		}
	}

	/**
	 * 检测是否正在下拉刷新
	 * 
	 * @return
	 */
	public boolean isRefreshing() {
		return isRefreshing;
	}

	/**
	 * 获取分页请求的起始点
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return startIndex;
	}

	/**
	 * 获取分页请求的结束点
	 * 
	 * @return
	 */
	public int getEndIndex() {
		return endIndex;
	}

	public void autoRefresh() {
		mPullRefreshListView.setRefreshing();
	}

	/**
	 * 设置是否允许item点击事件
	 * 
	 * @param enableItemClickListener
	 */
	public void enbaleItemClickListener(boolean enableItemClickListener) {
		if (enableItemClickListener) {
			mListView.setOnItemClickListener(this);
		} else {
			mListView.setOnItemClickListener(null);
		}
	}

	/**
	 * 显示无数据时的说明
	 * 
	 * @param img
	 *            无数据显示的图片资源
	 * @param desc
	 *            文字说明
	 */
	public void showNoDataInfo(int img, String desc) {
		ViewUtils.goneView(mPullRefreshListView);
		ViewUtils.showView(noDataLayout);
		ViewUtils.setImageSrc(noDataImg, img);
		ViewUtils.showText(noDataInfo, desc);
	}

	/**
	 * 显示listview
	 */
	public void showRefereshListView() {
		ViewUtils.showView(mPullRefreshListView);
		ViewUtils.goneView(noDataLayout);
	}

	/**
	 * 移除footview
	 */
	public void removeFootView() {
		mListView.removeFooterView(loadMoreManager.getFootView());
	}

	/**
	 * 禁止item点击事件
	 */
	public void disableItemClick() {
		setItemClickListener(null);
	}

	/**
	 * 设置item点击事件监听器
	 * 
	 * @param listener
	 */
	public void setItemClickListener(OnItemClickListener listener) {
		mListView.setOnItemClickListener(listener);
	}

	/**
	 * @param mOnScrollListener
	 *            the mOnScrollListener to set
	 */
	public void setOnScrollListener(OnScrollListener mOnScrollListener) {
		loadMoreManager.setOnScrollListener(mOnScrollListener);
	}

	private void setupRefreshSoundListener(boolean isEnableRefreshSound) {
		if (isEnableRefreshSound) {
			mPullRefreshListView.setOnPullEventListener(soundListener);
		} else {
			mPullRefreshListView.setOnPullEventListener(null);
		}
	}

	private void setLoadIndex(boolean reset) {
		if (reset) {
			// 起始请求
			startIndex = ALLocalEnv.LOAD_MORE_START_INDEX;
			// 结束请求
			endIndex = ALLocalEnv.LOAD_MORE_END_INDEX;
		} else {
			startIndex = adapter.getRealCount();
			endIndex = startIndex + ALLocalEnv.LOAD_MORE_COUNT_PER_TIME;
		}
	}

	/**
	 * 初始化布局文件
	 */
	private void initView(Context context) {
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.base_pull_refresh_list_layout, this);
		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);

		// mPullRefreshListView.setScrollingWhileRefreshingEnabled(false);

		mListView = mPullRefreshListView.getRefreshableView();

		loadMoreManager = new AbsListViewLoadMoreManager(mListView,
				ALLocalEnv.getLocalEnv());
		loadMoreManager.setOnLoadMoreListener(loadMoreListener);

		mListView.setOnItemClickListener(this);
		mListView.setSelector(R.drawable.list_default_selector);

		if (header != null) {
			mListView.addHeaderView(header);
		}

		mListView.setAdapter(adapter);

		mPullRefreshListView.setOnRefreshListener(pullRefreshListener);

		addSoundListener();

		// 初始化无数据布局
		noDataLayout = findViewById(R.id.no_data_layout);
		// 初始化无数据图片
		noDataImg = (ImageView) findViewById(R.id.no_data_img);
		// 初始化无数据说明
		noDataInfo = (TextView) findViewById(R.id.no_data_info);
	}

	/**
	 * 下拉刷新监听器
	 */
	private OnRefreshListener<ListView> pullRefreshListener = new OnRefreshListener<ListView>() {

		@Override
		public void onRefresh(PullToRefreshBase<ListView> refreshView) {
			// TODO Auto-generated method stub
			
			if(!isLocalData){
				if(!ALLocalEnv.isSendXmppDataEnable()){
					onLoadCompleted();
					return;
				}
			}
			
			if (isRefreshing) {
				ALLog.d("卡住了");
				return;
			}
			isRefreshing = true;
			String label = DateUtils.formatDateTime(ALLocalEnv.getLocalEnv(),
					System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
							| DateUtils.FORMAT_SHOW_DATE
							| DateUtils.FORMAT_ABBREV_ALL);

			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

			setLoadIndex(true);
			if (loadStateListener != null) {
				ALLog.d("执行下拉刷新，回调通知开始重新加载");
				loadStateListener.onRefresh(PullRefreshAndLoadMoreView.this);
			}

			// requestDiscoveryUsersList(false, false);
		}

	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
	 * .AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
		// TODO Auto-generated method stub
		if (id == -1) {
			// 点击的是headerView或者footerView
			return;
		}
		int realPosition = (int) id;
		User u = (User) adapter.getItem(realPosition);
		Intent intent = new Intent(ALActivityManager.getALActivityManager()
				.getCurrentActivity(), UserHomePageAcitivty.class);
		intent.putExtra("user", u);
		ALActivityManager.getALActivityManager().getCurrentActivity()
				.startActivity(intent);
	}

}
